<template>
  <div class="home">
    <h1>欢迎来到 Vue 在线数码购物商城</h1>
    <div class="carousel">
      <el-carousel height="400px" indicator-position="outside" :interval="5000" arrow="always" autoplay>
        <el-carousel-item v-for="product in products" :key="product.id">
          <div class="carousel-item">
            <img v-for="(image, index) in product.imageUrl" :key="`${product.id}-image-${index}`" :src="image" class="carousel-image" alt="Product image">
            <div class="carousel-caption">
              <h3>{{ product.name }}</h3>
              <p>{{ product.description }}</p>
            </div>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>
    <router-link to="/products" class="browse-link">浏览产品</router-link>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';

const products = ref([]);

// 从后端获取商品数据
const fetchProducts = async () => {
  try {
    const response = await axios.get('http://localhost:8080/api/product/getAllProducts');
    products.value = response.data.map(product => ({
      ...product,
      // 将 imageUrl 字符串分割成数组
      imageUrl: product.imageUrl
        ? product.imageUrl.split('，').map(img => `/src${img.substring(2)}`) // 使用逗号分隔符并处理图片路径
        : [] // 如果没有 imageUrl，则返回空数组
    }));
  } catch (error) {
    console.error("获取商品数据失败:", error);
  }
};

// 在组件挂载时获取数据
onMounted(async () => {
  await fetchProducts();
  console.log(products.value); // 检查返回的数据结构是否包含正确的 `imageUrl`
});
</script>

<style scoped>
.home {
  text-align: center;
  margin: 20px;
}

.carousel {
  margin: 20px 0;
}

.carousel-item {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.carousel-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: cover;
  border-radius: 10px;
  margin: 5px;
}

.carousel-caption {
  position: absolute;
  bottom: 20px;
  left: 20px;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  padding: 10px;
  border-radius: 5px;
}

.browse-link {
  display: inline-block;
  margin-top: 20px;
  padding: 10px 20px;
  background-color: #409EFF;
  color: white;
  text-decoration: none;
  border-radius: 5px;
  transition: background-color 0.3s ease;
}

.browse-link:hover {
  background-color: #66b1ff;
}
</style>